//配置路由
import Vue from "vue";
import VueRouter from "vue-router";

import Home from "@/pages/Home";
import Login from "@/pages/Login";
import Search from "@/pages/Search";
import Register from "@/pages/Register";
import Detail from '@/pages/Detail';
import AddCartSuccess from '@/pages/AddCartSuccess';
import ShopCart from '@/pages/ShopCart';
import store from '@/store';
import Trade from '@/pages/Trade';
import Pay from '@/pages/Pay';
import PaySuccess from '@/pages/PaySuccess';
import Center from '@/pages/Center';
import MyCenter from '@/pages/Center/MyCenter';
import GroupCenter from '@/pages/Center/GroupCenter';


Vue.use(VueRouter);

//解决（编程式导航）频繁出错
// 重写push
const origiPush = VueRouter.prototype.push;
VueRouter.prototype.push = function (location, resolve, reject) {
    if (resolve && reject) {
        origiPush.call(this, location, resolve, reject);
    } else {
        origiPush.call(this, location, () => { }, () => { });
    }
}
// 重写replace
const origiReplace = VueRouter.prototype.replace;
VueRouter.prototype.replace = function (location, resolve, reject) {
    if (resolve && reject) {
        origiReplace.call(this, location, resolve, reject);
    } else {
        origiReplace.call(this, location, () => { }, () => { });
    }
}


//解决（编程式导航）频繁出错
// const Catch = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) { return Catch.call(this, location).catch(err => err) }



const router = new VueRouter({
    routes: [
        {
            path: '/center',
            name: 'center',
            component: Center,
            meta: { show: true },
            children: [
                {
                    path: 'mycenter',
                    component: MyCenter
                },
                {
                    path: 'groupcenter',
                    component: GroupCenter
                },
                {
                    path: '/center',
                    redirect: 'mycenter'
                }
            ]
        },
        {
            path: '/paysuccess',
            name: 'paysuccess',
            component: PaySuccess,
            meta: { show: true }
        },
        {
            path: '/pay',
            name: 'pay',
            component: Pay,
            meta: { show: true },
            beforeEnter: (to, from, next) => {
                if (from.path == '/trade') {
                    next();
                } else {
                    next(false);
                }
            }
        },
        {
            path: '/trade',
            name: 'trade',
            component: Trade,
            meta: { show: true },
            beforeEnter: (to, from, next) => {
                //去交易页面，必须式从购物车而来
                if (from.path == '/shopcart') {
                    next();
                } else {
                    //其他的路由组件而来，停留在当前
                    next(false);
                }
            }
        },
        {
            path: '/shopcart',
            name: 'shopcart',
            component: ShopCart,
            meta: { show: true }
        },
        {
            path: '/addcartsuccess',
            name: 'addcartsuccess',
            component: AddCartSuccess,
            meta: { show: true }
        },
        {
            path: '/detail/:skuId',
            component: Detail,
            meta: { show: true }
        },
        {
            path: '/home',
            component: Home,
            meta: { show: true }
        },
        {
            path: '/login',
            component: Login,
            meta: { show: false }
        },
        {
            name: 'search',
            path: '/search/:keyword?',
            component: Search,
            meta: { show: true },
            // props: true  布尔值写法
            // props: { a: 1, b: 2 } 对象写法
            props($route) {  //函数写法
                return { keyword: $route.params.keyword }
            }
        },
        {
            path: '/register',
            component: Register,
            meta: { show: false }
        },
        {
            path: '*',
            redirect: '/home'
        }
    ],
    //滚动行为
    scrollBehavior(to, from, savedPosition) {
        //与顶部位置，代表滚动条在最上方
        return { y: 0 }
    }
});

router.beforeEach(async (to, from, next) => {
    let token = store.state.user.token;
    let name = store.state.user.userInfo.name;
    if (token) {
        if (to.path === '/login') {
            next('false');
        } else {
            if (name) {
                next();
            } else {
                try {
                    await store.dispatch("getUserInfo");
                    next();
                } catch (error) {
                    await store.dispatch('getUserLogout');
                    next('/login');
                }
            }
        }
    } else {
        let toPath = to.path;
        if (toPath.indexOf('/trade') != -1 || toPath.indexOf('/pay') != -1 || toPath.indexOf('/center') != -1) {
            //把未登录的时候想去而没有去成的信息，存储于地址栏中【路由】
            next('/login?redirect=' + toPath);
        } else {
            //去的不是上面这些路由---放行
            next();
        }
    }
})


export default router;